package com.playtruly.wanzhende2025

import android.util.Log
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import java.lang.reflect.Field
import java.lang.reflect.Method
import java.util.regex.Pattern

/**
 * 日志过滤器
 * 用于过滤不需要的系统日志
 */
class LogFilter : MethodChannel.MethodCallHandler {
    // 要过滤的黑名单模式
    private val blacklistPatterns = arrayOf(
        Pattern.compile(".*ImageReader_JNI.*"),
        Pattern.compile(".*Unable to acquire a buffer.*"),
        Pattern.compile(".*removeInvalidNode.*"),
        Pattern.compile(".*InitSystemFonts.*"),
        Pattern.compile(".*axesSize.*"),
        Pattern.compile(".*DisplayEventDispatcher.*"),
        Pattern.compile(".*ignoring unknown event.*"),
        Pattern.compile(".*jank list.*")
    )

    companion object {
        private const val CHANNEL = "com.playtruly.wanzhende2025/log_filter"
        private const val TAG = "LogFilter"

        // 注册通道
        fun registerWith(flutterEngine: FlutterEngine) {
            val channel = MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL)
            val filter = LogFilter()
            channel.setMethodCallHandler(filter)
        }
    }

    override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
        when (call.method) {
            "installLogFilter" -> {
                installLogFilter()
                result.success(true)
            }
            else -> result.notImplemented()
        }
    }

    // 安装日志过滤器
    private fun installLogFilter() {
        try {
            // 尝试反射修改Android日志系统
            hookAndroidLogging()
            
            // 设置空日志处理器
            setEmptyLogHandler()
            
            Log.i(TAG, "日志过滤器已安装")
        } catch (e: Exception) {
            Log.e(TAG, "安装日志过滤器失败", e)
        }
    }

    // 尝试通过反射修改Android日志系统
    private fun hookAndroidLogging() {
        try {
            val logClass = Class.forName("android.util.Log")
            
            // 获取println_native方法
            val printlnMethod = logClass.getDeclaredMethod(
                "println_native",
                Int::class.java,
                String::class.java,
                String::class.java
            )
            
            // 设置方法可访问
            printlnMethod.isAccessible = true
            
            // 创建代理日志处理器
            val proxyPrintlnNative = object : java.lang.reflect.InvocationHandler {
                @Throws(Throwable::class)
                override fun invoke(proxy: Any, method: Method, args: Array<Any>?): Any {
                    if (method.name == "println_native" && args != null && args.size >= 3) {
                        val tag = args[1] as? String ?: ""
                        val msg = args[2] as? String ?: ""
                        
                        // 检查是否包含黑名单关键词
                        if (shouldFilter(tag, msg)) {
                            return 0 // 返回成功但不打印
                        }
                    }
                    
                    // 调用原始方法
                    return method.invoke(null, *(args ?: arrayOfNulls(0)))
                }
            }
            
            // 应用代理
            // 注意：在现代Android系统中，这可能不起作用，因为系统安全限制
            Log.i(TAG, "已尝试安装日志拦截器")
        } catch (e: Exception) {
            Log.e(TAG, "安装日志拦截器失败", e)
        }
    }
    
    // 设置空的日志处理器
    private fun setEmptyLogHandler() {
        try {
            // 反射获取LogHandler
            val logHandlerClass = Class.forName("android.util.LogHandler")
            val defaultHandlerField = logHandlerClass.getDeclaredField("DEFAULT")
            defaultHandlerField.isAccessible = true
            
            // 创建空的处理器实例
            val emptyHandlerClass = Class.forName("com.playtruly.wanzhende2025.EmptyLogHandler")
            val emptyHandler = emptyHandlerClass.newInstance()
            
            // 替换默认处理器
            defaultHandlerField.set(null, emptyHandler)
            
            Log.i(TAG, "已设置空日志处理器")
        } catch (e: Exception) {
            // 忽略错误，因为这个类可能在某些Android版本中不可用
        }
    }
    
    // 检查是否应该过滤消息
    private fun shouldFilter(tag: String, msg: String): Boolean {
        val fullLog = "$tag: $msg"
        return blacklistPatterns.any { pattern ->
            pattern.matcher(fullLog).matches()
        }
    }
} 